package com.example.demo01.controller;

import com.example.demo01.exception.UserNotExistException;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyControllerAdvice {

    /**
     * 1.浏览器、客户端返回的都是 json 数据
     */
//    @ResponseBody
//    @ExceptionHandler(UserNotExistException.class)
//    public Map<String, Object> handleException(Exception e) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", "user.notExist");
//        map.put("message", e.getMessage());
//        return map;
//    }

    /**
     * 自适应: 转发到 /error 进行自适应响应效果处理
     *
     * @see BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
     */
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", "user.notExist");
        map.put("message", e.getMessage());
        map.put("company", "角落处的一抹微光");
        request.setAttribute("ext", map);
        // TODO: Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code", 500);
        // TODO: 转发到 /error 让 SpringBoot 自适应处理
        return "forward:/error";
    }
}
